using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SqlTools.SchemaReader
{
	public class Check : DbTextObject
	{
		protected Column _column;
		protected int _tableID;

		public Check() : this("", 0, 0) { }

		public Check(string name, int id, int tableid)
			: base(name, id)
		{
			_column = null;
			_tableID = tableid;
		}

		public Column Column
		{
			get { return _column; }
			internal set { _column = value; }
		}

		public int TableID
		{
			get { return _tableID; }
		}

		public override DbObjectType Type
		{
			get { return DbObjectType.Check; }
		}

		public override XmlElement CreateXmlElement(XmlDocument doc, XmlNode parent)
		{
			XmlElement el = base.CreateXmlElement(doc, parent);

			el.Attributes.Append(doc.CreateAttribute("tableid")).Value = _tableID.ToString();
			
			if ( _column != null )
				el.Attributes.Append(doc.CreateAttribute("columnid")).Value = _column.ID.ToString();

			return el;
		}

		public override void LoadXml(XmlElement el, Database db)
		{
			base.LoadXml(el, db);

			string tableID = el.GetAttribute("tableid");
			string columnid = el.GetAttribute("columnid");

			db.Checks.Add(this);

			if ( int.TryParse(tableID, out _tableID) )
			{
				// load table
				Table table = db.Tables.RetrieveByID(_tableID);

				if ( table != null )
				{
					// load column
					int column = 0;

					if ( int.TryParse(columnid, out column) )
					{
						_column = table.Columns.RetrieveByID(column);
						_column.Check = this;
					}
				}
			}
			else
			{
				_tableID = 0;
			}
		}
	}
}
